package com.gmldd.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public class DBCPUtils {
	private static DataSource ds;
	static {
		try {
			InputStream in = DBCPUtils.class.getClassLoader()
					.getResourceAsStream("dbcpconfig.properties");
			Properties props = new Properties();
			props.load(in);
			ds = BasicDataSourceFactory.createDataSource(props);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static DataSource getDs() {
		return ds;
	}

	// 2. 从数据源中获取连接对象
	public static Connection getConnection(){
		try {
			return ds.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	// 3. 关闭连接
	public static void close(Connection con) {
		try {
			if (con != null && !con.isClosed()) {
				con.close();
				con = null; // 建议回收资源
			}
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

}
